import time

from fastapi import FastAPI,Request
from starlette.staticfiles import StaticFiles

from download_api import router as download_router
from ytdlp_download import get_video_path,get_poster_path
from fastapi.responses import JSONResponse
import json
import dao


class UTF8JSONResponse(JSONResponse):
    def render(self, content: any) -> bytes:
        return json.dumps(content, ensure_ascii=False).encode("utf-8")
app = FastAPI(default_response_class=UTF8JSONResponse)

@app.middleware("http")
async def add_utf8_charset(request: Request, call_next):
    # 处理请求并获取响应
    response = await call_next(request)
    # 统一设置 Content-Type 包含 charset=utf-8
    if "Content-Type" in response.headers:
        # 如果已有 Content-Type，检查并追加 charset=utf-8
        content_type = response.headers["Content-Type"]
        if "charset=" not in content_type:
            response.headers["Content-Type"] = f"{content_type}; charset=utf-8"
    else:
        # 如果没有 Content-Type，设置为默认的 application/json; charset=utf-8
        response.headers["Content-Type"] = "application/json; charset=utf-8"
    return response


app.include_router(download_router,prefix="/api")

@app.get("/")
async def root():
    return {"message": "你好世界"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}


app.mount("/video", StaticFiles(directory=get_video_path()), name="video")
app.mount("/poster", StaticFiles(directory=get_poster_path()), name="poster")
